package middleware.solr;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;

import java.io.IOException;
import java.util.*;

/**
 * Solrj 测试类
 *
 * @author ME
 * @date   2019/3/22 11:19
 */
public class TestSolrj {

    private static String solrBaseUrl = "http://134.96.179.123:8080/hzsolr";

    /**
     * 查询solr
     *
     * @param entityType 准备查询的 solr core
     * @param conditions 查询条件
     * @return
     * @throws Exception
     */
    public static List<Map<String, Object>> queryBySolr(String entityType, Map<String, Object> conditions) throws SolrServerException {

        String solrUrl = solrBaseUrl;
        if (!solrUrl.endsWith("/")) {
            solrUrl = solrUrl + "/";
        }

        solrUrl += entityType;

        HttpSolrServer server = new HttpSolrServer(solrUrl);
        SolrQuery query = new SolrQuery();
        // SolrQuery 的其他参数设置
        // query.addFilterQuery("");
        // query.setSort("", ORDER.asc);
        // query.setFields("");
        query.setRows(Integer.MAX_VALUE);

        // 写法1.0
        String queryStr = "";// 拼装查询
        for (Map.Entry<String, Object> entity : conditions.entrySet()) {
            String key = entity.getKey();
            Object value = entity.getValue();
            if (value != null && !"".equals(value)) {
                queryStr = queryStr + key + ":(" + value + ") ";
            } else {
                queryStr = queryStr + key + ":* ";
            }
        }
        query.setQuery(queryStr);

        // 写法2.0
        // String queryStr = "";// 拼装查询
        // for (Map.Entry<String, Object> entity : conditions.entrySet()) {
        //     String key = entity.getKey();
        //     Object value = entity.getValue();
        //     if (value != null && !"".equals(value)) {
        //         queryStr = queryStr + key + ":" + value + " AND ";
        //     } else {
        //         queryStr = queryStr + key + ":* AND ";
        //     }
        // }
        // query.setQuery(queryStr);

        QueryResponse resp = server.query(query);
        SolrDocumentList docs = resp.getResults();
        List<Map<String, Object>> resultlist = new ArrayList<Map<String, Object>>();
        for (SolrDocument doc : docs) {
            Map<String, Object> map = new HashMap<String, Object>();
            Collection<String> names = doc.getFieldNames();
            for (Iterator<String> iterator = names.iterator(); iterator.hasNext(); ) {
                String key =  iterator.next();
                map.put(key, doc.getFieldValue(key));
            }
            resultlist.add(map);
        }

        return resultlist;
    }

    public static String print(List<Map<String, Object>> maps) {
        String s = "[";
        for (Map<String, Object> map : maps) {
            s = s + "ID: " + map.get("ID") + ", FULLNAME: " + map.get("FULLNAME");
        }
        return s + "]\n";
    }

    /**
     *
     * @param args Program arguments 的配置项
     * @throws SolrServerException
     * @throws IOException
     */
    public static void main(String[] args) throws SolrServerException, IOException {
        // 用户的账户名称
        System.out.printf("user.name                : %s\n", System.getProperty("user.name"));
        // 用户的主目录
        System.out.printf("user.home                : %s\n", System.getProperty("user.home"));
        // 用户的当前工作目录
        System.out.printf("user.dir                 : %s\n", System.getProperty("user.dir"));
        System.out.printf("java.net.preferIPv4Stack : %s\n\n", System.getProperty("java.net.preferIPv4Stack"));

        // 用户目录
        System.out.printf("USERPROFILE  : %s\n", System.getenv("USERPROFILE"));
        // 用户域
        System.out.printf("USERDNSDOMAIN: %s\n", System.getenv("USERDNSDOMAIN"));
        // 用户临时文件目录
        System.out.printf("TEMP         : %s\n", System.getenv("TEMP"));
        // Session名
        System.out.printf("SESSIONNAME  : %s\n", System.getenv("SESSIONNAME"));

        // http 方式
        // HttpClient client = new DefaultHttpClient();
        // HttpGet get = new HttpGet("http://admin:12345@134.96.179.68:8806/lssolr/address/dataimport?command=full-import");
        // HttpResponse response = client.execute(get);
        // System.out.println(response.getStatusLine().getStatusCode());

        // SolrServer server = new HttpSolrServer("http://admin:12345@134.96.179.68:8806/lssolr/address");
        // // 删除
        // // server.deleteById("2333");
        // // server.commit();
        //
        // // 新增
        // SolrInputDocument doc = new SolrInputDocument();
        // doc.addField("ID", "2333");
        // doc.addField("FULLNAME", new Object[]{"我就是个测试地址~~~"});
        // server.add(doc);
        // server.commit();
        //
        // // full-import
        // try {
        //     ModifiableSolrParams params = new ModifiableSolrParams();
        //     // qt会优先翻译成 path的值
        //     params.set("qt", "/dataimport");
        //     params.set("command", "full-import");
        //     // params.set("clean", "true");// 默认clean=true
        //     QueryResponse res = server.query(params);
        //     System.out.println(res);
        // } catch (SolrServerException e1) {
        //     e1.printStackTrace();
        // }

        /*
         * SolrUtil 并发测试！！！ t1 线程设置好参数后睡眠1s，t2线程直接查询，
         */
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> conditions = new HashMap<String, Object>();
                conditions.put("ID", "331000000000100995212138");
                //				FULLNAME: 杭州市富阳市新登镇登城路医药公司宿舍楼1单元501
                try {
                    List<Map<String, Object>> result = TestSolrj.queryBySolr("address", conditions);
                    System.out.println(TestSolrj.print(result));
                } catch (SolrServerException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> conditions = new HashMap<String, Object>();
                conditions.put("ID", "331000000000100995212235");
                //				FULLNAME: 杭州市桐庐县桐君街道富春路4幢4单元707
                try {
                    List<Map<String, Object>> result = TestSolrj.queryBySolr("address", conditions);
                    System.out.println(TestSolrj.print(result));
                } catch (SolrServerException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}
